package com.cl.web.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class BaseAction<T> extends ActionSupport implements ModelDriven<T>{
	
	protected static final String LIST = "list";
	protected static final String NONE = "none";
	protected static final String LOGIN = "login";
	protected static final String HOME = "home";
	protected int page;
	protected int limit;
	protected DetachedCriteria dc;
	protected T model;
	
	public BaseAction() {
		ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
		Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
		Class<T> entityClass = (Class<T>) actualTypeArguments[0];
		dc = DetachedCriteria.forClass(entityClass);
		try {
			model = entityClass.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
	
	public void ObjectToJson(Object obj) throws IOException{
		JsonConfig config = new JsonConfig();
		config.setExcludes(new String[]{"cutterPage","pageSize","start"});
		JSONObject json = JSONObject.fromObject(obj, config);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8");
		PrintWriter pw = response.getWriter();
		pw.print(json.toString());
		pw.close();
	}
	
	public void ObjectToJson(Object obj, String[] arrConfig) throws IOException{
		JsonConfig config = new JsonConfig();
		config.setExcludes(arrConfig);
		JSONObject json = JSONObject.fromObject(obj, config);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8");
		PrintWriter pw = response.getWriter();
		pw.print(json.toString());
		pw.close();
	}
	
	public void ListToJson(List list, String[] arrConfig) throws IOException{
		JsonConfig config = new JsonConfig();
		config.setExcludes(arrConfig);
		JSONArray json = JSONArray.fromObject(list, config);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8");
		PrintWriter pw = response.getWriter();
		pw.print(json.toString());
		pw.close();
	}
	
	@Override
	public T getModel() {
		return model;
	}
	
	public void setPage(int page) {
		this.page = page;
	}


	public void setLimit(int limit) {
		this.limit = limit;
	}

}
